import { defineConfig } from 'vite';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';
import path from 'path';
import type { Plugin } from 'vite';

// 处理__dirname在ESM中的兼容
const __dirname = path.dirname(fileURLToPath(import.meta.url));

const generateDtsPlugin: Plugin = {
  name: 'generate-dts',
  // 构建完成后执行
  closeBundle() {
    try {
      // 执行tsc生成类型声明
      execSync('tsc --emitDeclarationOnly', { stdio: 'inherit' });
      console.log('✅ 类型声明文件已生成到dist目录');
    } catch (error) {
      console.error('❌ 类型声明生成失败:', error);
    }
  }
};

export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, 'src/index.ts'),
      name: 'vitePluginVersionJson',
      formats: ['es'],
      fileName: (format) => `index.js`
    },
    rollupOptions: {
      external: ['child_process', 'fs', 'path', 'vite'],
      output: {
        exports: 'named',
        banner: '/*! vite-plugin-version-json - MIT License */',
        interop: 'auto'
      }
    },
    outDir: 'dist',
    sourcemap: false,
    minify: true
  },
  plugins: [generateDtsPlugin]
});
